﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

namespace mfe.lib
{
    public class Imaging
    {
        /// <summary>
        /// Add a watermark to an image.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="watermark"></param>
        public static void Watermark(string source, string watermark)
        {
            try
            {
                Image imageSource = Image.FromFile(source);
                Image imageWatermark = Image.FromFile(watermark);
                Bitmap bitmap = new Bitmap(imageSource.Width, imageSource.Height, PixelFormat.Format24bppRgb);
                bitmap.SetResolution(imageSource.HorizontalResolution, imageSource.VerticalResolution);
                Graphics g = Graphics.FromImage(bitmap);
                g.DrawImage(imageSource, new Rectangle(0, 0, imageSource.Width, imageSource.Height), 0, 0, imageSource.Width, imageSource.Height, GraphicsUnit.Pixel);
                ImageAttributes imageAttributes = new ImageAttributes();
                //coordinates for the RGBA space, [3][3] set the level of opacity
                float[][] colorMatrixElements = { 
                  new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, 
                  new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, 
                  new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, 
                  new float[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, 
                  new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};
                ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
                imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                int xPosOfWm = ((imageSource.Width - imageWatermark.Width) / 2);
                int yPosOfWm = ((imageSource.Height - imageWatermark.Height) / 2);
                g.DrawImage(imageWatermark, new Rectangle(xPosOfWm, yPosOfWm, imageWatermark.Width, imageWatermark.Height), 0, 0, imageWatermark.Width, imageWatermark.Height, GraphicsUnit.Pixel, imageAttributes);
                imageSource.Dispose();
                bitmap.Save(source, ImageFormat.Jpeg);
                bitmap.Dispose();
                imageWatermark.Dispose();
                g.Dispose();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
                throw ex;
            }
        }


        public static void Watermark2()
        {
            //set a working directory
            string WorkingDirectory = @"C:\Documents and Settings\administrator.JAZZMINE\My Documents\Projects\Tutorials\WaterMark";

            //define a string of text to use as the Copyright message
            string Copyright = "Copyright © 2002 - AP Photo/David Zalubowski";

            //create a image object containing the photograph to watermark
            Image imgPhoto = Image.FromFile(WorkingDirectory + "\\watermark_photo.jpg");
            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //create a Bitmap the Size of the original photograph
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //load the Bitmap into a Graphics object 
            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            //create a image object containing the watermark
            Image imgWatermark = new Bitmap(WorkingDirectory + "\\watermark.bmp");
            int wmWidth = imgWatermark.Width;
            int wmHeight = imgWatermark.Height;

            //------------------------------------------------------------
            //Step #1 - Insert Copyright message
            //------------------------------------------------------------

            //Set the rendering quality for this Graphics object
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //Draws the photo Image object at original size to the graphics object.
            grPhoto.DrawImage(
                imgPhoto,                               // Photo Image object
                new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
                0,                                      // x-coordinate of the portion of the source image to draw. 
                0,                                      // y-coordinate of the portion of the source image to draw. 
                phWidth,                                // Width of the portion of the source image to draw. 
                phHeight,                               // Height of the portion of the source image to draw. 
                GraphicsUnit.Pixel);                    // Units of measure 

            //-------------------------------------------------------
            //to maximize the size of the Copyright message we will 
            //test multiple Font sizes to determine the largest posible 
            //font we can use for the width of the Photograph
            //define an array of point sizes you would like to consider as possiblities
            //-------------------------------------------------------
            int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

            Font crFont = null;
            SizeF crSize = new SizeF();

            //Loop through the defined sizes checking the length of the Copyright string
            //If its length in pixles is less then the image width choose this Font size.
            for (int i = 0; i < 7; i++)
            {
                //set a Font object to Arial (i)pt, Bold
                crFont = new Font("arial", sizes[i], FontStyle.Bold);
                //Measure the Copyright string in this Font
                crSize = grPhoto.MeasureString(Copyright, crFont);

                if ((ushort)crSize.Width < (ushort)phWidth)
                    break;
            }

            //Since all photographs will have varying heights, determine a 
            //position 5% from the bottom of the image
            int yPixlesFromBottom = (int)(phHeight * .05);

            //Now that we have a point size use the Copyrights string height 
            //to determine a y-coordinate to draw the string of the photograph
            float yPosFromBottom = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));

            //Determine its x-coordinate by calculating the center of the width of the image
            float xCenterOfImg = (phWidth / 2);

            //Define the text layout by setting the text alignment to centered
            StringFormat StrFormat = new StringFormat();
            StrFormat.Alignment = StringAlignment.Center;

            //define a Brush which is semi trasparent black (Alpha set to 153)
            SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));

            //Draw the Copyright string
            grPhoto.DrawString(Copyright,                 //string of text
                crFont,                                   //font
                semiTransBrush2,                           //Brush
                new PointF(xCenterOfImg + 1, yPosFromBottom + 1),  //Position
                StrFormat);

            //define a Brush which is semi trasparent white (Alpha set to 153)
            SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

            //Draw the Copyright string a second time to create a shadow effect
            //Make sure to move this text 1 pixel to the right and down 1 pixel
            grPhoto.DrawString(Copyright,                 //string of text
                crFont,                                   //font
                semiTransBrush,                           //Brush
                new PointF(xCenterOfImg, yPosFromBottom),  //Position
                StrFormat);                               //Text alignment



            //------------------------------------------------------------
            //Step #2 - Insert Watermark image
            //------------------------------------------------------------

            //Create a Bitmap based on the previously modified photograph Bitmap
            Bitmap bmWatermark = new Bitmap(bmPhoto);
            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            //Load this Bitmap into a new Graphic Object
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //To achieve a transulcent watermark we will apply (2) color 
            //manipulations by defineing a ImageAttributes object and 
            //seting (2) of its properties.
            ImageAttributes imageAttributes = new ImageAttributes();

            //The first step in manipulating the watermark image is to replace 
            //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
            //to do this we will use a Colormap and use this to define a RemapTable
            ColorMap colorMap = new ColorMap();

            //My watermark was defined with a background of 100% Green this will
            //be the color we search for and replace with transparency
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //The second color manipulation is used to change the opacity of the 
            //watermark.  This is done by applying a 5x5 matrix that contains the 
            //coordinates for the RGBA space.  By setting the 3rd row and 3rd column 
            //to 0.3f we achive a level of opacity
            float[][] colorMatrixElements = { 
												new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},       
												new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},        
												new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},        
												new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},        
												new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}};
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                ColorAdjustType.Bitmap);

            //For this example we will place the watermark in the upper right
            //hand corner of the photograph. offset down 10 pixels and to the 
            //left 10 pixles

            int xPosOfWm = ((phWidth - wmWidth) - 10);
            int yPosOfWm = 10;

            grWatermark.DrawImage(imgWatermark,
                new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight),  //Set the detination Position
                0,                  // x-coordinate of the portion of the source image to draw. 
                0,                  // y-coordinate of the portion of the source image to draw. 
                wmWidth,            // Watermark Width
                wmHeight,		    // Watermark Height
                GraphicsUnit.Pixel, // Unit of measurment
                imageAttributes);   //ImageAttributes Object

            //Replace the original photgraphs bitmap with the new Bitmap
            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();

            //save new image to file system.
            imgPhoto.Save(WorkingDirectory + "\\watermark_final.jpg", ImageFormat.Jpeg);
            imgPhoto.Dispose();
            imgWatermark.Dispose();

        }

        /// <summary>
        /// Create a thumbnail of the source image, with the desired width. 
        /// </summary>
        /// <param name="source">The full path to the source image.</param>
        /// <param name="destFileName">The full path to the final output.</param>
        /// <param name="desiredWidth">The width of the thumbnail, height will be proportionally calculated.</param>
        public static string ThumbnailImage(string source, string destFileName, int desiredWidth)
        {
            if (!System.IO.File.Exists(source))
                throw new System.IO.FileNotFoundException();

            System.Drawing.Image image = System.Drawing.Image.FromFile(source);
            int srcWidth = image.Width;
            int srcHeight = image.Height;
            Decimal sizeRatio = ((Decimal)srcHeight / srcWidth);
            int thumbHeight = Decimal.ToInt32(sizeRatio * desiredWidth);
            Bitmap bmp = new Bitmap(desiredWidth, thumbHeight);
            try
            {

                System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
                gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, desiredWidth, thumbHeight);
                gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
                bmp.Save(destFileName);
                bmp.Dispose();
                //int width, height;
                //width = desiredWidth;
                //height = (int)((double)image.Height / ((double)image.Width / (double)width));
                //// create the actual thumbnail image
                //System.Drawing.Image thumbnailImage = image.GetThumbnailImage(width, height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

                //thumbnailImage.Save(destFileName, ImageFormat.Jpeg);
                //image.Dispose();
                //thumbnailImage.Dispose();

                return destFileName;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
                throw ex;
            }
            finally
            {
                image.Dispose();
            }
        }

        public static byte[] ThumbnailImage(FileStream fs, int desiredWidth)
        {
            if (fs == null)
                throw new System.NullReferenceException("Destination image cannot be null.");


            Image data = Image.FromStream(fs);
            byte[] retval = null;
            Decimal sizeRatio = ((Decimal)data.Height / data.Width);
            int thumbHeight = Decimal.ToInt32(sizeRatio * desiredWidth);
            Bitmap bmp = new Bitmap(desiredWidth, thumbHeight);


            try
            {


                System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
                gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, desiredWidth, thumbHeight);
                gr.DrawImage(data, rectDestination, 0, 0, data.Width, data.Height, GraphicsUnit.Pixel);
                using (MemoryStream ms = new MemoryStream())
                {
                    bmp.Save(ms, ImageFormat.Jpeg);
                    retval = ms.ToArray();
                }
                bmp.Dispose();


                //return destFileName;
            }
            catch (Exception ex)
            {
                mfe.lib.Logger.Log(ex);
            }


            return retval;
        }

        public static byte[] ThumbnailImage_dev(FileStream fs, int desiredWidth)
        {
            /* if the width of the image is smaller than the desiredWidth, frame the image with white space.
             * */
            if (fs == null)
                throw new System.NullReferenceException("Destination image cannot be null.");

            int tempDesiredWidth = desiredWidth;
            Image data = Image.FromStream(fs);
            byte[] retval = null;
            Decimal sizeRatio = ((Decimal)data.Height / data.Width);

            List<Rectangle> rects = new List<Rectangle>();
            if (data.Width <= desiredWidth)
            {
                desiredWidth = data.Width;
                //create the rect that will hold the white space
                Rectangle r = new Rectangle(
                    data.Width,
                    0,
                    tempDesiredWidth - data.Width,
                    data.Height);
                rects.Add(r);
            }

            int thumbHeight = Decimal.ToInt32(sizeRatio * desiredWidth);

            if (thumbHeight < tempDesiredWidth)
            {
                Rectangle r = new Rectangle(
                    0,
                    data.Height,
                    tempDesiredWidth,
                    tempDesiredWidth - data.Height);
                rects.Add(r);
            }

            Bitmap bmp = new Bitmap(tempDesiredWidth, tempDesiredWidth);

            try
            {

                System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
                gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, desiredWidth, thumbHeight);
                gr.DrawImage(data, rectDestination, 0, 0, data.Width, data.Height, GraphicsUnit.Pixel);
                foreach (Rectangle r in rects)
                {
                    gr.DrawRectangle(new Pen(Brushes.Red), r);
                }
                using (MemoryStream ms = new MemoryStream())
                {
                    bmp.Save(ms, ImageFormat.Jpeg);
                    retval = ms.ToArray();
                }
                bmp.Dispose();

                //return destFileName;
            }
            catch (Exception ex)
            {
                mfe.lib.Logger.Log(ex);
            }

            return retval;
        }
        /// <summary>
        /// Required for generating thumbnail, but not used
        /// </summary>
        /// <returns>true</returns>
        static bool ThumbnailCallback()
        {
            return true;
        }

        public static void CaptchaImage(string destFileName)
        {
        }
    }
}

